<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\model\forest\Order as ForestOrder;
use app\common\model\LeatLog;
use app\common\model\MoneyLog;
use app\common\model\Order;
use app\common\model\order\Point;
use app\common\model\Out;
use app\common\model\product\Member;
use app\common\model\product\Order as ProductOrder;
use app\common\model\ScoreLog;
use app\common\model\Survey;
use app\common\model\User as ModelUser;
use app\common\model\user\Address;
use app\common\model\user\Withdrawal;
use app\common\model\Wxpay;
use fast\Date;
use fast\Random;
use think\Config;
use think\Db;
use think\Log;
use think\Session;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'wxLogin', 'changemobile', 'miniLogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $userInfo = $this->auth->getUser();
        $uids =  ModelUser::where('pid', $userInfo['id'])->column('id');
        $user_ids_count =  ModelUser::whereIn('pid', $uids)->count();
        $userInfo['teamNum'] = count($uids) + $user_ids_count;
        $userInfo['firstNum'] = ModelUser::where('pid', $userInfo['id'])->count();
        $user_ids =  ModelUser::where('pid', $userInfo['id'])->column('id');
        $userInfo['twoNum'] = $user_ids_count;
        $userInfo['totalMoney'] = $userInfo['money'] + $userInfo['freeze_money'] + $userInfo['no_withdraw'];
        $sn = ProductOrder::whereIn('user_id', $user_ids + $uids)->where('status', '1')->column('sn');
        $sn += Order::whereIn('user_id', $user_ids + $uids)->where('status', '>', 0)->column('sn');
        $sn += ForestOrder::whereIn('user_id', $user_ids + $uids)->where('status', '1')->column('sn');
        $uids =  ModelUser::where('pid', $userInfo['id'])->column('id');
        $userInfo['reward'] = MoneyLog::where('user_id', $this->auth->id)->whereIn('order_sn', $sn)->where('money', '>', 0)->sum('money');
        $performance = Order::whereIn('id', $uids)->where('status', '>', 0)->sum('pay_money');
        $performance += ProductOrder::whereIn('id', $uids)->where('status', 1)->sum('price');
        if ($performance > 0) {
            $year = Date::span($userInfo->createtime, time(), 'years');
            if ($year['years'] < 1) {
                $fee = bcmul($userInfo->gold_leaf * 3000, 0.5, 2);
            } else if ($year['years'] >= 1 && $year['years'] < 2) {
                $fee = bcmul($userInfo->gold_leaf, 3000, 2);
            } else if ($year['years'] >= 2 && $year['years'] < 3) {
                $fee = bcmul($userInfo->gold_leaf * 3000, 1.5, 2);
            } else if ($year['years'] >= 3) {
                $fee = bcmul($userInfo->gold_leaf * 3000, 2, 2);
            }
        } else {
            $fee = bcmul($userInfo->gold_leaf * 3000, 0.5, 2);
        }
        $userInfo['fee'] = $fee;
        $this->success('', $userInfo);
    }
    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if ($captcha != '1234') {
            if (!Sms::check($mobile, $captcha)) {
                $this->error(__('Captcha is incorrect'));
            }
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $this->success(__('Sign up successful'), $this->auth->getUserinfo());
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();

        // $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $code = $this->request->post('code');
        $status = $this->request->post('status');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if (!$user->pid && $code) {
            $p_user = \app\common\model\User::get(['code' => $code]);
            if (isset($p_user) && !empty($p_user)) {
                $user->pid = $p_user->id;
                $pUser = \app\common\model\User::get($user->pid);
                if ($pUser) {
                    $user->paren_ids = trim($pUser['paren_ids'] . ',' . $user->pid, ',');
                }
            } else {
                $this->error(__('请填写真实邀请码'));
            }
        }
        // $user->bio = $bio;
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($status) {
            $user->status = 'hidden';
        }
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }
    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    // public function third()
    // {
    //     $url = url('user/index');
    //     $platform = $this->request->post("platform");
    //     $code = $this->request->post("code");
    //     $config = get_addon_config('third');
    //     if (!$config || !isset($config[$platform])) {
    //         $this->error(__('Invalid parameters'));
    //     }
    //     $app = new \addons\third\library\Application($config);
    //     //通过code换access_token和绑定会员
    //     $result = $app->{$platform}->getUserInfo(['code' => $code]);
    //     if ($result) {
    //         $loginret = \addons\third\library\Service::connect($platform, $result);
    //         if ($loginret) {
    //             $data = [
    //                 'userinfo'  => $this->auth->getUserinfo(),
    //                 'thirdinfo' => $result
    //             ];
    //             $this->success(__('Logged in successful'), $data);
    //         }
    //     }
    //     $this->error(__('Operation failed'), $url);
    // }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 微信登录
     *
     * @return array
     */
    public function wxLogin()
    {
        $params = $this->request->param();
        extract($params);
        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxAppProgram');
            $decryptData = $wechat->wxAppLogin($code);
            if (!$decryptData || !isset($decryptData['openid']) || !isset($decryptData['unionid'])) {
                Log::error('未获取到登录状态：' . json_encode($decryptData));
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptData['openid']) || empty($decryptData['unionid'])) {
                exception('code错误,请重试!');
            }
            if (isset($decryptData['openid'])) {
                $where['openid'] = ['=', $decryptData['openid']];
            }
            if (isset($decryptData['unionid'])) {
                $where['unionid'] = ['=', $decryptData['unionid']];
            }
            $user = \app\common\model\User::get($where);
            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                // 直接登陆
                $result = $this->auth->direct($user->id);
            } else {
                // 写入个人数据
                if (isset($share_code) && !empty($share_code)) {
                    $p_user = \app\common\model\User::get(['code' => $share_code]);
                    if (isset($p_user) && !empty($p_user)) {
                        $decryptData['pid'] = $p_user['id'];
                    }
                }
                $result = $this->auth->oauthRegister($decryptData);
            }
        } catch (\Exception $e) {
            Log::error('登录失败：' . $e->getMessage());
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!');
        }
    }
    /**
     * @Author LK
     * @ApiTitle (微信小程序登录)
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="integer", required=true, sample="", description="登录code")
    //  * @ApiParams (name="phoneCode", type="integer", required=true, sample="", description="手机code")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function miniLogin()
    {
        $params = $this->request->param();
        extract($params);
        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            if (empty($decryptSession['openid']) ) {
                exception('code错误,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            if (isset($decryptSession['openid'])) {
                $where['openid'] = ['=', $decryptSession['openid']];
            }
            // if (isset($decryptSession['unionid'])) {
            //     $where['unionid'] = ['=', $decryptSession['unionid']];
            // }
            // $res = $wechat->getPhone($phoneCode);
            // if ($res['errcode'] == 0) {
            //     $phone = $res['phone_info'];
            //     $where['mobile'] = $phone['phoneNumber'];
            // } else {
            //     exception('失败:' . $res['errmsg']);
            // }
            // 分参
            $user = \app\common\model\User::get($where);
            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                $result = $this->auth->direct($user->id, $decryptSession);
            } else {
                // $decryptSession['mobile'] = $phone['phoneNumber'];
                $result = $this->auth->oauthRegister($decryptSession);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!' . $this->auth->getError());
        }
    }
    /**
     * 获取用户收货地址
     *
     * @ApiMethod (GET)
     */
    public function getUserAddress()
    {
        $uid = $this->auth->id;
        $data = Address::getUserAddress($uid);
        $this->success('获取成功', $data);
    }
    /**
     * 获取用户默认地址
     *
     * @ApiMethod (GET)
     */
    public function getDefaultAddress()
    {
        $uid = $this->auth->id;
        $list = Address::getDefaultAddress($uid);
        $this->success('获取成功', $list);
    }
    /**
     * 设置用户默认地址
     *
     * @ApiMethod (GET)
     */
    public function setDefaultAddress()
    {
        $id = $this->request->post('id');
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        Address::setDefaultAddress($id, $uid);
        $this->success('设置成功');
    }
    /**
     * 添加收货地址
     *
     * @ApiMethod (GET)
     */
    public function addAddress()
    {
        $post = $this->request->post();
        $validate = validate('user.Address'); //使用助手函数
        $result = $validate->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        $post['user_id'] = $this->auth->id;
        $res = Address::AddAddress($post);
        if ($res !== false) {
            $this->success('提交成功', $res);
        }
        $this->error('提交失败');
    }
    /**
     * 删除用户收货地址
     *
     * @ApiMethod (POST)
     */
    public function delAddress()
    {
        if (!$this->request->isPost()) {
            $this->error('请求方式错误');
        }
        $id = $this->request->post('id');
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        $data = Address::get($id);
        $data->delete();
        $this->success('删除成功', $data);
    }
    /**
     * 检查问卷状态
     *
     * @ApiMethod (POST)
     */
    public function checkSurvey()
    {
        $uid = $this->auth->id;
        $num = Survey::where('user_id', $uid)->count();
        if ($num == 1) {
            $params = Survey::where('user_id', $uid)->order('id asc')->find();
            $time = strtotime("+1 month", $params['createtime']);
            if (time() < $time) {
                $this->error('请服食一个月后再来填写', '', -1);
            }
        }
        if ($num == 2) {
            $params = Survey::where('user_id', $uid)->order('id asc')->find();
            $time = strtotime("+3 month", $params['createtime']);
            if (time() < $time) {
                $this->error('填写时间未到', '', -1);
            }
        }
        if ($num >= 3) {
            $this->error('您已全部提交完毕');
        }
        $this->success();
    }
    /**
     * 问卷调查提交
     *
     * @ApiMethod (POST)
     */
    public function survey()
    {
        $post = request()->post();
        extract($post);
        $user_id = $this->auth->id;
        $data = [
            'name' => $name,
            'phone' => $phone,
            'age' => $age,
            'medical_history' => $medical_history,
            'year' => $year ?? 0,
            'stomach' => $stomach ? $stomach : null,
            'fasting_index' => $fasting_index ? $fasting_index : null,
            'after_dinner' => $after_dinner ? $after_dinner : null,
            'postprandial_index' => $postprandial_index ? $postprandial_index : null,
            'user_id' => $user_id,
        ];
        Db::startTrans();
        try {
            $survey = new Survey($data);
            $res = $survey->allowField(true)->save();
            ScoreLog::income($user_id, 200, 2, 100, $survey->id);
            $user = new ModelUser();
            $user->save(['group_id' => 1], ['id' => $user_id]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('提交失败');
        }

        if ($res) {
            $this->success('提交成功');
        }
    }
    /**
     * 积分兑换记录
     *
     * @ApiMethod (GET)
     */
    public function pointsRecordLog()
    {
        $point = new Point;
        $list = $point->where('user_id', $this->auth->id)->order('id desc')->paginate(10);
        $this->success('', $list);
    }

    /**
     * 用户提现
     *
     */
    public function withdrawal()
    {
        $post = $this->request->post();
        $user = $this->auth->getUserinfo();
        extract($post);
        $min_withdrawn = config('site.min_withdrawn');
        if ($money < $min_withdrawn) {
            $this->error('最低提现' . $min_withdrawn);
        }
        if ($user['money'] < $money) {
            $this->error('GR积分不足');
        }
        if (!isset($openid) || !$openid) {
            $this->error('尚未授权微信，无法提现');
        }
        $withdrawal_commission = config('site.withdraw_fee') ?? 0;
        if ($withdrawal_commission > 0 && $withdrawal_commission <= 100) {
            $handling_charge = bcmul($money, $withdrawal_commission / 100, 2);
        }
        Db::startTrans();
        try {
            $amount_received = bcsub($money, $handling_charge, 2);
            $res = Wxpay::withdrawal($amount_received, $openid);
            if ($res) {
                $post['sn'] = sn('user_withdrawal', 'sn', 'TX');
                $post['user_id'] = $user['id'];
                $post['batch_id'] = $res['batch_id'];
                $post['handling_charge'] = $handling_charge;
                $post['amount_received'] = $amount_received;
                $tx = new Withdrawal($post);
                $tx->allowField(true)->save();
                MoneyLog::income($user['id'], $money, 1, 300, $post['sn']);
            }
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage() . $th->getLine());
        }
        $this->success('申请成功');
    }
    /**
     * 提现明细
     *
     */
    public function withdrawalInfo()
    {
        $tx = new Withdrawal();
        $list = $tx->where('user_id', $this->auth->id)->paginate();
        $this->success('', $list);
    }
    /**
     * 用户团队
     *
     */
    public function my_team()
    {
        $get = request()->get();
        extract($get);
        if (!isset($get) || empty($get)) {
            $this->error('参数错误');
        }
        if (isset($keywords) && $keywords) {
            $where['nickname|mobile'] = ['like', '%' . $keywords . '%'];
        }
        $uid = $this->auth->id;
        $uids =  ModelUser::where('pid', $uid)->column('id');
        if ($type == 1) {
            $where['pid'] = ['=', $uid];
            $users =  ModelUser::where($where)->field('id,avatar,nickname,mobile,jointime,validitytime,leaf_level')->paginate(10);
        } elseif ($type == 2) {
            if ($uids) {
                $where['pid'] = ['in', $uids];
            } else {
                $where['pid'] = ['=', null];
            }
            $users =  ModelUser::where($where)->field('id,avatar,nickname,mobile,jointime,validitytime,leaf_level')->paginate(10);
        }
        $this->success('', $users);
    }
    /**
     * 团队奖励
     *
     */
    public function my_team_reward()
    {
        $get = request()->get();
        extract($get);
        $where = [];
        if (isset($keywords) && $keywords) {
            $where['mobile'] = ['like', '%' . $keywords . '%'];
        }
        $uid = $this->auth->id;
        $uids =  ModelUser::where('pid', $uid)->column('id');
        $user_ids =  ModelUser::whereIn('pid', $uids)->field('id,avatar,nickname,mobile,jointime,validitytime,leaf_level')->column('id');
        $users =  ModelUser::where('id', 'in', $user_ids + $uids)->where($where)->field('id,avatar,nickname,mobile,jointime,validitytime,leaf_level')->paginate(10);
        foreach ($users as $k => $v) {
            $sn = ProductOrder::where('user_id', $v->id)->where('status', '1')->column('sn');
            $sn += Order::where('user_id', $v->id)->where('status', '>', 0)->column('sn');
            $sn += ForestOrder::where('user_id', $v->id)->where('status', '1')->column('sn');
            $v->reward = MoneyLog::where('user_id', $this->auth->id)->whereIn('order_sn', $sn)->where('money', '>', 0)->sum('money');
        }
        $this->success('', $users);
    }
    /**
     * GS明细
     *
     */
    public function gsDetails()
    {
        $get = request()->get();
        extract($get);
        if (!isset($type) || !$type) {
            $this->error('参数错误');
        }
        $list = ScoreLog::where('type', $type)->where('user_id', $this->auth->id)->order('id desc')->paginate(10);
        $this->success('', $list);
    }
    /**
     * GR明细
     *
     */
    public function grDetails()
    {
        $get = request()->get();
        extract($get);
        if (!isset($type) || !$type) {
            $this->error('参数错误');
        }
        $list = MoneyLog::where('type', $type)->where('user_id', $this->auth->id)->order('id desc')->paginate(10);
        $this->success('', $list);
    }

    /**
     * @Author LK
     * @date: 2025-06-05 17:59:05
     * @ApiTitle (兑换金叶子)
     * @ApiMethod (POST)
     * @ApiParams (name="type", type="integer", required=true, sample="", description="1=GS兑换金叶子,2=GR兑换金叶子")
     * @ApiParams (name="num", type="string", required=true, sample="", description="兑换金叶子数量")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function exchange()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            ['type', 'require', '参数错误'],
            ['num', 'require|number', '请输入金叶子数量|请输入金叶子数量'],
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        Db::startTrans();
        try {
            if ($type == 1) {
                $total = $num * 12000;
                if ($total > $this->auth->score) {
                    exception('GS积分不足');
                }
                $msg = 'GS兑换金叶子';
                ScoreLog::income($this->auth->id, $total, 1, 301);
            }
            if ($type == 2) {
                $total = $num * 3000;
                if ($total > $this->auth->money) {
                    exception('GR积分不足');
                }
                $msg = 'GR兑换金叶子';
                MoneyLog::income($this->auth->id, $total, 1, 800);
            }
            $total_leaf = ModelUser::sum('gold_leaf');
            if ($total_leaf < 300000) {
                if ($total_leaf + $num > 300000) {
                    $leaf = bcsub(300000, $total_leaf, 0);
                } else {
                    $leaf = $num;
                }
                ModelUser::leaf($leaf, $this->auth->id, $msg);
            }
            //检查金叶子是否满足升级条件
            $user = ModelUser::get($this->auth->id);
            ModelUser::checkLeafUpgrade($user);
            //检查上级创客是否满足升级条件
            $puser = ModelUser::get($this->auth->pid);
            if ($puser && $puser['leaf_level'] == 1) {
                ModelUser::checkUpgrade($user, $puser);
            }
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('兑换成功');
    }

    /**
     * @Author LK
     * @date: 2025-06-05 18:21:13
     * @ApiTitle (积分转赠金叶子)
     * @ApiMethod (POST)
     * @ApiParams (name="num", type="string", required=true, sample="", description="转赠金叶子数量")
     * @ApiParams (name="user_id", type="string", required=true, sample="", description="受赠人")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function give_leaf()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            ['num', 'require|number', '请输入金叶子数量|请输入金叶子数量'],
            ['user_id', 'require', '受赠人不能为空'],
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        Db::startTrans();
        try {
            $user =  ModelUser::get($user_id);
            ModelUser::leaf(-$num, $this->auth->id, "转赠金叶子给【{$user->nickname}】");
            ModelUser::leaf($num, $user_id,  "【{$this->auth->nickname}】转增金叶子");
            //检查金叶子是否满足升级条件
            $user = ModelUser::get($user_id);
            ModelUser::checkLeafUpgrade($user);
            //检查上级创客是否满足升级条件
            $puser = ModelUser::get($user->pid);
            if ($puser && $puser['leaf_level'] == 1) {
                ModelUser::checkUpgrade($user, $puser);
            }
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('转赠成功');
    }

    /**
     * 金叶子明细
     *
     */
    public function give_Details()
    {
        $get = request()->get();
        extract($get);
        $list = LeatLog::where('user_id', $this->auth->id)->order('id desc')->paginate(10);
        $this->success('', $list);
    }

    /**
     * @Author LK
     * @date: 2025-06-17 13:50:05
     * @ApiTitle (退出金叶子)
     * @ApiMethod (POST)
     * @ApiParams (name="num", type="string", required=true, sample="", description="金叶子数量")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({"code":0,"msg":"返回成功"})
     */
    public function leafout()
    {
        $num = $this->request->post('num');
        if (!$num) {
            $this->error("请输入金叶子数量");
        }
        if ($num > $this->auth->gold_leaf) {
            $this->error("金叶子不足");
        }
        Db::startTrans();
        try {
            $user = $this->auth->getUser();
            $time = time();
            $direct = ModelUser::where('pid', $user->id)->column('id');
            $performance = Order::whereIn('id', $direct)->where('status', '>', 0)->sum('pay_money');
            $performance += ProductOrder::whereIn('id', $direct)->where('status', 1)->sum('price');
            if ($performance > 0) {
                $year = Date::span($user->createtime, $time, 'years,months');
                if ($year['years'] < 1) {
                    $fee = bcmul($num * 3000, 0.5, 2);
                } else if ($year['years'] >= 1 && $year['years'] < 2) {
                    $fee = bcmul($num, 3000, 2);
                } else if ($year['years'] >= 2 && $year['years'] < 3) {
                    $fee = bcmul($num * 3000, 1.5, 2);
                } else if ($year['years'] >= 3) {
                    $fee = bcmul($num * 3000, 2, 2);
                }
            } else {
                $fee = bcmul($num * 3000, 0.5, 2);
            }

            ModelUser::leaf(-$num, $this->auth->id, '退出金叶子');
            Out::create([
                'user_id' => $this->auth->id,
                'leaf' => $num,
                'fee' => $fee,
                'outtime' => $time,
            ]);
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }

        $this->success("请求成功");
    }
}
